package com.member.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.member.common.utils.SmsUtil;
import com.member.common.utils.UUIDUtil;
import com.member.entity.Messages;
import com.member.entity.MessagesRecord;
import com.member.entity.User;
import com.member.entity.base.BaseModel;
import com.member.entity.vo.BusinessManagerOrOrganizer;
import com.member.entity.vo.UserVo;
import com.member.mapper.MessageMapper;
import com.member.mapper.UserMapper;
import com.member.service.MessageService;

@Service
public class MessageServiceImpl implements MessageService {

	@Autowired
	MessageMapper messageMapper;
	@Autowired
	UserMapper userMapper;

	@Override
	public BaseModel insertMessage(String managerName, String address, String organizerName,String title, String content) {
		BaseModel result=new BaseModel();
		Map<String, Object> map = new HashMap<>();
		map.put("state", "0");
		if (!"0".equals(managerName)) {
			map.put("businessManager1", managerName);
		}
		if (!"0".equals(address)) {
			map.put("address1", address);
		}
		if (!"0".equals(organizerName)) {
			map.put("organizerName", organizerName);
		}
		List<User> list = userMapper.findAllByFilter(map);
		System.out.println("找到会员数量："+list.size());
		if (null != list && list.size() > 0) {
			Messages message=new Messages();
			message.setId(UUIDUtil.getRandom32PK());
			message.setTitle(title);
			message.setContent(content);
			message.setSize(list.size());
			message.setState(0);
			messageMapper.insert(message);
	
			 for(int i=0;i<list.size();i++){
					Boolean smsResult=SmsUtil.sendHuiYuanMessage(list.get(i).getPhone(), list.get(i).getName(), title, content, message.getId());
					MessagesRecord record=new MessagesRecord();
					record.setMessageId(message.getId());
					record.setName(list.get(i).getName());
					record.setPhone(list.get(i).getPhone());
					
					if(smsResult){
						result.Successful=true;
						record.setState(1);
						messageMapper.insertMessage(record);
					}else{
						result.Successful=false;
						result.Message="抱歉发送给"+list.get(i).getName()+"的"+list.get(i).getPhone()+" 短信通知失败";
						record.setState(2);
						messageMapper.insertMessage(record);
						break;
					}
			 }
		} else {
			result.Successful=false;
			result.Message="抱歉没有找到对应的会员，发送 短信通知失败";

		}
		return result;
	}

	@Override
	public List<BusinessManagerOrOrganizer> select(String id) {
		List<BusinessManagerOrOrganizer> a = new ArrayList<>();
		if (id.equals("1")) {
			a = messageMapper.selectBusinessManager();
		}
		if (id.equals("2")) {
			a = messageMapper.selectOrganizer();
		}
		return a;
	}

	@Override
	public List<UserVo> selectUser(String id) {
		return messageMapper.selectUser(id);
	}

}
